import { onBeforeUnmount, onMounted, ref } from 'vue';

export function useWebSocket(
  url: string | URL,
  handleMessage?: (message: string) => void,
) {
  const socket = ref<WebSocket | null>(null); // 保存 WebSocket 实例
  const isConnected = ref(false); // 用于标识是否连接成功
  const message = ref<string[]>([]);
  const error = ref(null); // 保存错误信息

  // 连接 WebSocket
  const connect = () => {
    socket.value = new WebSocket(url);

    // 监听连接成功
    socket.value.onopen = () => {
      isConnected.value = true;
      console.log('WebSocket 连接成功');
    };

    // 监听消息
    socket.value.onmessage = (event) => {
      console.log('收到消息:', event.data);
      if (event.data === 'pong') return;
      message.value.push(event.data);
      handleMessage?.(event.data);
    };

    // 监听错误
    socket.value.onerror = (err) => {
      console.error('WebSocket 错误:', err);
    };

    // 监听连接关闭
    socket.value.onclose = () => {
      isConnected.value = false;
      console.log('WebSocket 已断开');
    };
  };

  // 断开 WebSocket 连接
  const disconnect = () => {
    if (socket.value) {
      socket.value.close();
    }
  };

  // 发送消息
  const sendMessage = (message: string) => {
    if (socket.value && isConnected.value) {
      socket.value.send(message);
      console.log('发送消息:', message);
    }
  };

  // 清空消息
  const cleanMessage = () => {
    message.value = [];
  };

  // 在组件挂载时连接 WebSocket
  onMounted(() => {
    connect();
  });

  // 在组件销毁前关闭 WebSocket 连接
  onBeforeUnmount(() => {
    disconnect();
  });

  return {
    isConnected,
    error,
    message,
    sendMessage,
    disconnect,
    cleanMessage,
  };
}
